import { AfterViewInit, Component, OnInit, TemplateRef } from '@angular/core';
import { FormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { BehaviorSubject } from 'rxjs';
import { Consts } from 'src/app/consts/consts';
import { EditMode } from 'src/app/models/enums/edit-mode.enum';
import { PostQueryParam } from 'src/app/models/param/post-query.param';
import { PostDto } from 'src/app/models/sys/post.dto';
import { ApiService } from 'src/app/services/api.service';
import { ContentHeaderService } from 'src/app/services/content-header.service';

const POST_NAME = 'postName';
const POST_CODE = 'postCode';
const ENABLED = 'enabled';

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrl: './post.component.less'
})
export class PostComponent implements OnInit, AfterViewInit {
  searchForm!: UntypedFormGroup;
  submitted = false;

  // Post Table
  posts: PostDto[] = [];
  pageIndex = 1;
  pageSize = 10;
  total = 0;

  // Modal
  modeSubject = new BehaviorSubject<{ mode: EditMode, post?: PostDto }>({ mode: EditMode.ADD, post: undefined });

  // 对话框title
  editTitle?: string;
  postName?: string;

  // 详情
  postSubject = new BehaviorSubject<PostDto>(new PostDto());


  constructor(private _api: ApiService,
    private _fb: FormBuilder,
    private _modal: NzModalService,
    private _message: NzMessageService,
    private _contentHeader: ContentHeaderService) { }

  ngAfterViewInit(): void {
    setTimeout(() => {
      this._contentHeader.header.next('岗位管理');
    });
  }

  ngOnInit(): void {
    console.log('dept on init called');
    this.createSearchForm();
    this.onSearch();
  }

  createSearchForm() {
    this.searchForm = this._fb.group({});
    this.searchForm.addControl(POST_NAME, new UntypedFormControl('', [Validators.maxLength(50)]));
    this.searchForm.addControl(POST_CODE, new UntypedFormControl('', [Validators.maxLength(64)]));
    this.searchForm.addControl(ENABLED, new UntypedFormControl(''));
  }

  get fm() {
    return this.searchForm.controls;
  }

  onSearch() {
    this.submitted = true;
    if (!this.searchForm.valid) {
      return;
    }

    const param = new PostQueryParam();
    param.postName = this.searchForm.get('postName')?.value;
    param.postCode = this.searchForm.get('postCode')?.value;
    param.enabled = this.searchForm.get('enabled')?.value;
    param.pageNum = this.pageIndex;
    param.pageSize = this.pageSize;

    this._api.getPostList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.posts = resp.data;
        this.total = resp.total;
      }

      this.submitted = false;
    });
  }

  onCreate(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>) {
    this.resetModal();
    this.editTitle = '创建岗位';
    this.postName = undefined;

    this._modal.create({
      nzTitle: this.editTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('post added');
      }
    });

    this.modeSubject.next({ mode: EditMode.ADD, post: undefined });
  }

  onUpdate(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, post: PostDto) {
    console.log('OnUpdate Dept');
    this.resetModal();
    this.editTitle = '编辑岗位';
    this.postName = post.postName;

    this._modal.create({
      nzTitle: this.editTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('dept added');
      }
    });

    this.modeSubject.next({ mode: EditMode.EDIT, post: post });
  }

  onDetail(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, post: PostDto) {
    this.editTitle = '岗位详情';

    this._modal.create({
      nzTitle: this.editTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 1024,
      nzOnOk: () => {
        console.log('groupType detail');
      }
    });

    this.postSubject.next(post);
  }

  onDelete(id: number) {
    console.log(`To delete dept of ${id}`);
    this._api.deletePost(id).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("删除岗位成功");
        this.onSearch();
      } else {
        this._message.warning("删除岗位失败：" + resp.message);
      }
    });
  }

  onReset() {
    this.searchForm.get(POST_NAME)?.setValue(undefined);
    this.searchForm.get(POST_CODE)?.setValue(undefined);
    this.searchForm.get(ENABLED)?.setValue(undefined);
    this.submitted = false;
  }

  resetModal() {
    this.editTitle = "添加岗位";
  }

  onAddPostEvent(result: boolean) {
    console.log(`add dept result ${result}`);

    this._modal.closeAll();
    if (result) {
      this.onSearch();
    }
  }

  onPageParamChange(params: NzTableQueryParams) {
    this.pageIndex = params.pageIndex;
    this.pageSize = params.pageSize;
    this.onSearch();
  }

  onDetailEvent(result: boolean) {
    this._modal.closeAll();
    console.log(`${result}`);
  }
}
